#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

#define LEFT 	30000000
#define RIGHT 	30000200
#define THRNUM 	4

//参数结构体
struct thr_arg_st
{
	int n;
};

static int num = 0;
//初始化互斥量
static pthread_mutex_t mutex_num = PTHREAD_MUTEX_INITIALIZER;
//初始化条件变量
static pthread_cond_t cond_num = PTHREAD_COND_INITIALIZER;

//线程处理函数
static void * thr_primer(void * p)
{
	int i;
	int j;
	while(1)
	{
		pthread_mutex_lock(&mutex_num);					//上锁
		while(num == 0)
		{
			pthread_cond_wait(&cond_num, &mutex_num);	//等待条件变量被唤醒
		}
		if(num == -1)
		{
			pthread_mutex_unlock(&mutex_num);
			break;//注意临界区内的所有跳转！！！！！！！
		}
		i = num;
		num = 0;
		pthread_cond_broadcast(&cond_num);				//唤醒所有其他人
		pthread_mutex_unlock(&mutex_num);				//上锁

		int mark = 1;
		for(j = 2; j < i / 2; j ++)
		{
			if(i % j == 0)
				{
					mark = 0;
					break;
				}
		}
		if(mark == 1)
			printf("[%d]:%d is a primer\n", ((struct thr_arg_st *)p)->n, i);
	}
	pthread_exit(NULL);
}

int main()
{
	int i, err;
	pthread_t tid[THRNUM];
	struct thr_arg_st * p;

	//创建线程
	for(i = 0; i < THRNUM; i++)
	{
		//为参数申请空间
		p = malloc(sizeof(*p));
		if(p == NULL)
		{
			perror("malloc");
			exit(1);
		}
		//为参数赋值
		p->n = i;
		err = pthread_create(&tid[i], NULL, thr_primer, p);
		if(err)
		{
			fprintf(stderr, "create:%s", strerror(err));
			exit(1);
		}
	}
	//分发任务
	for(i = LEFT; i < RIGHT; i ++)
	{
		pthread_mutex_lock(&mutex_num);					//上锁
		while(num != 0)
		{
			pthread_cond_wait(&cond_num, &mutex_num);	//等待被唤醒
		}
		num = i;
		pthread_cond_signal(&cond_num);					//叫醒任意一个
		pthread_mutex_unlock(&mutex_num);				//解锁
	}

	pthread_mutex_lock(&mutex_num);						//上锁
	while(num != 0)
	{
		pthread_cond_wait(&cond_num, &mutex_num);		//等待被唤醒
	}
	num = -1;
	pthread_cond_broadcast(&cond_num);					//唤醒其他所有人
	pthread_mutex_unlock(&mutex_num);					//解锁

	//回收所有线程
	for(i = 0; i < THRNUM; i++)
	{
		err = pthread_join(tid[i], NULL);
	}
	//销毁互斥锁
	pthread_mutex_destroy(&mutex_num);
	//销毁条件变量
	pthread_cond_destroy(&cond_num);

	exit(0);
}